// Copyright 2006 Bret Taylor
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

#ifndef INDIE_MEMORY_H__
#define INDIE_MEMORY_H__

#include <algorithm>

namespace indie {

template<class Collection>
class auto_collection_ptr {
  public:
    auto_collection_ptr(Collection* collection) : collection_(collection) {
    }

    ~auto_collection_ptr() {
	if (collection_ != NULL) {
	    std::for_each(collection_->begin(), collection_->end(),
			  DeleteFunctor());
	    delete collection_;
	}
    }

    Collection* get() const throw() {
	return collection_;
    }

    Collection* operator->() const throw() {
	return collection_;
    }

    Collection& operator*() const throw() {
	return *collection_;
    }

    Collection* release() throw() {
	Collection* c = collection_;
	collection_ = NULL;
	return c;
    }

  private:
    class DeleteFunctor {
      public:
	template<class Type>
	void operator()(Type *t) {
	    delete t;
	}
    };

    Collection* collection_;
};

}

#endif // INDIE_MEMORY_H__
